#include <string>
#include<array>
#include<limits>

class Solution
{
public:
    int balancedString(std::string s)
    {
        std::array<int, 4> cnt;
        cnt.fill(0);
        int debt = 0;
        int n = s.size();
        for (int i = 0; i < n; i++)
        {
            switch (s[i])
            {
            case'Q':
                s[i] = 0;
                cnt[0]--;
                break;
            case'W':
                cnt[1]--;
                s[i] = 1;
                break;
            case'E':
                cnt[2]--;
                s[i] = 2;
                break;
            case'R':
                cnt[3]--;
                s[i] = 3;
                break;
            default:
                s[i] = 4;
                break;
            }
        }
        for (int i = 0; i < 4; i++)
        {
            if (-cnt[i] > n / 4)
            {
                cnt[i] += n/4;
                debt -= cnt[i];
            }
            else
            {
                cnt[i] = 0;
            }
        }
        int ans = std::numeric_limits<int>::max();
        for (int r = 0, l = 0; r < n; r++)
        {
            if (cnt[s[r]] < 0)
            {
                debt--;
            }
            if (s[r] < 4)
                cnt[s[r]]++;
            if (debt <= 0)
            {
                while (cnt[s[l]] > 0)
                {
                    cnt[s[l++]]--;
                }
                ans = std::min(ans, r - l + 1);
            }
        }
        return ans;
    }
};

